package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.business.BusinessDO;
import com.qk.domain.business.BusinessPoolDO;
import com.qk.dto.business.BusinessAddDTO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessFollowDTO;
import com.qk.dto.business.BusinessPoolDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Author ZgYn
 * @Date 2025/10/15 10:54
 * @Name BusinessServiceImpl
 */
@Slf4j
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private BusinessTrackRecordMapper btrMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public PageResult<BusinessDO> getList(BusinessDTO dto) {
        Page<Object> page = new Page<>(dto.getPage(), dto.getPageSize());

        Page<BusinessDO> businessPage = this.baseMapper.selectByPage(page, dto);

        return PageResult.<BusinessDO>builder()
                .total(Long.valueOf(businessPage.getTotal()).intValue())
                .rows(businessPage.getResult())
                .build();
    }

    @Override
    public void addBusiness(BusinessAddDTO dto) {
        if (ObjectUtil.hasNull(dto.getName()) || ObjectUtil.hasNull(dto.getPhone())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.TO_BE_FOLLOWED);
        this.baseMapper.insert(business);
    }

    @Override
    public BusinessVO getBusinessById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        BusinessVO vo = BeanUtil.copyProperties(business, BusinessVO.class);
        List<BusinessTrackRecord> businessTrackRecords = btrMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class).eq(BusinessTrackRecord::getBusinessId, id));
        businessTrackRecords.forEach(item->item.setAssignName(userMapper.selectNameById(item.getUserId())));
        vo.setTrackRecords(businessTrackRecords);
        return vo;
    }

    @Override
    @Transactional
    public void businessFollow(BusinessFollowDTO dto) {
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getName()) || ObjectUtil.isEmpty(dto.getTrackStatus())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        if (Objects.equals(business.getStatus(), BusinessStatusConstants.TO_BE_FOLLOWED)) {
            business.setStatus(BusinessStatusConstants.FOLLOWING);
        }
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);


        BusinessTrackRecord record = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        record.setBusinessId(dto.getId());
        log.info("businessId{}", record.getBusinessId());
        record.setCreateTime(LocalDateTime.now());
        record.setId(null);
        record.setUserId(CurrentUserContextHolders.get());
        log.info(record.toString());
        this.btrMapper.insert(record);
    }

    @Override
    public PageResult<BusinessPoolDO> getPool(BusinessPoolDTO dto) {
        Page<Object> page = new Page<>(dto.getPage(), dto.getPageSize());
        Page<BusinessPoolDO> businessPage = this.baseMapper.selectPoolByPage(page, dto);

        return PageResult.<BusinessPoolDO>builder()
                .total(Long.valueOf(businessPage.getTotal()).intValue())
                .rows(businessPage.getResult())
                .build();
    }

    @Override
    public void toCustomer(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.TO_CUSTOMER);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);

        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId(null);
        customer.setUpdateTime(LocalDateTime.now());
        customer.setCreateTime(LocalDateTime.now());
        this.customerMapper.insert(customer);
    }

    @Transactional
    @Override
    public void backToPool(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.RECOVERED);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
    }
}
